package com.lekang.system.service.impl;

import java.util.List;
import java.math.BigDecimal;
import com.lekang.common.utils.DateUtils;
import com.lekang.common.utils.SecurityUtils;
import com.lekang.system.domain.NursingItemPlanBinding;
import com.lekang.system.domain.NursingPlan;
import com.lekang.system.mapper.NursingItemPlanBindingMapper;
import com.lekang.system.mapper.NursingPlanMapper;
import com.lekang.system.service.INursingPlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 护理计划Service业务层处理
 *
 *
 * @date 2025-10-13
 */
@Service
public class NursingPlanServiceImpl implements INursingPlanService
{
    @Autowired
    private NursingPlanMapper nursingPlanMapper;

    @Autowired
    private NursingItemPlanBindingMapper nursingItemPlanBindingMapper;

    /**
     * 查询护理计划
     *
     * @param id 护理计划主键
     * @return 护理计划
     */
    @Override
    public NursingPlan selectNursingPlanById(Long id)
    {
        return nursingPlanMapper.selectNursingPlanById(id);
    }

    /**
     * 查询护理计划列表
     *
     * @param nursingPlan 护理计划
     * @return 护理计划
     */
    @Override
    public List<NursingPlan> selectNursingPlanList(NursingPlan nursingPlan)
    {
        return nursingPlanMapper.selectNursingPlanList(nursingPlan);
    }

    /**
     * 新增护理计划
     *
     * @param nursingPlan 护理计划
     * @return 结果
     */
    @Override
    @Transactional
    public int insertNursingPlan(NursingPlan nursingPlan)
    {
        nursingPlan.setCreateTime(DateUtils.getNowDate());
        nursingPlan.setCreator(SecurityUtils.getUserId());
        nursingPlan.setStatus(1L); // 默认启用状态
        nursingPlan.setIsDeleted(0L); // 默认未删除

        // 计算30天总价并写入extraField1，同时设置非持久化返回字段
        BigDecimal total = calculatePlanTotalPrice(nursingPlan);
        if (total != null) {
            nursingPlan.setExtraField1(total.toPlainString());
            nursingPlan.setTotalPrice(total);
        }

        int result = nursingPlanMapper.insertNursingPlan(nursingPlan);

        // 插入护理项目绑定关系
        if (result > 0 && nursingPlan.getNursingItemPlanBindingList() != null && !nursingPlan.getNursingItemPlanBindingList().isEmpty()) {
            for (NursingItemPlanBinding binding : nursingPlan.getNursingItemPlanBindingList()) {
                binding.setNursingPlanId(nursingPlan.getId());
            }
            nursingItemPlanBindingMapper.insertNursingItemPlanBindingBatch(nursingPlan.getNursingItemPlanBindingList());
        }

        return result;
    }

    /**
     * 修改护理计划
     *
     * @param nursingPlan 护理计划
     * @return 结果
     */
    @Override
    @Transactional
    public int updateNursingPlan(NursingPlan nursingPlan)
    {
        // 计算30天总价并写入
        BigDecimal total = calculatePlanTotalPrice(nursingPlan);
        if (total != null) {
            nursingPlan.setExtraField1(total.toPlainString());
            nursingPlan.setTotalPrice(total);
        }

        int result = nursingPlanMapper.updateNursingPlan(nursingPlan);

        // 更新护理项目绑定关系
        if (result > 0 && nursingPlan.getNursingItemPlanBindingList() != null) {
            // 先删除原有的绑定关系
            nursingItemPlanBindingMapper.deleteByNursingPlanId(nursingPlan.getId());

            // 再插入新的绑定关系
            if (!nursingPlan.getNursingItemPlanBindingList().isEmpty()) {
                for (NursingItemPlanBinding binding : nursingPlan.getNursingItemPlanBindingList()) {
                    binding.setNursingPlanId(nursingPlan.getId());
                }
                nursingItemPlanBindingMapper.insertNursingItemPlanBindingBatch(nursingPlan.getNursingItemPlanBindingList());
            }
        }

        return result;
    }

    /**
     * 批量删除护理计划
     *
     * @param ids 需要删除的护理计划主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteNursingPlanByIds(Long[] ids)
    {
        // 先删除绑定关系
        for (Long id : ids) {
            nursingItemPlanBindingMapper.deleteByNursingPlanId(id);
        }
        return nursingPlanMapper.deleteNursingPlanByIds(ids);
    }

    /**
     * 删除护理计划信息
     *
     * @param id 护理计划主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteNursingPlanById(Long id)
    {
        // 先删除绑定关系
        nursingItemPlanBindingMapper.deleteByNursingPlanId(id);
        return nursingPlanMapper.deleteNursingPlanById(id);
    }
    /**
     * 依据护理计划绑定的项目计算30天总价：
     * - 每日：执行次数/天 * 单价 * 30
     * - 每周：执行次数/周 * 单价 * 4（按4周近似）
     * - 每月：执行次数/月 * 单价 * 1
     */
    private BigDecimal calculatePlanTotalPrice(NursingPlan nursingPlan) {
        if (nursingPlan == null || nursingPlan.getNursingItemPlanBindingList() == null) {
            return BigDecimal.ZERO;
        }
        BigDecimal sum = BigDecimal.ZERO;
        for (NursingItemPlanBinding b : nursingPlan.getNursingItemPlanBindingList()) {
            if (b == null || b.getNursingItemId() == null) continue;
            // 通过自定义查询获取项目单价
            com.lekang.system.domain.NursingItem item = nursingItemPlanBindingMapper.selectItemPriceByItemId(b.getNursingItemId());
            if (item == null || item.getPrice() == null) continue;
            int freq = b.getExecutionFrequency() == null ? 1 : b.getExecutionFrequency();
            int cycle = b.getExecutionCycle() == null ? 1 : b.getExecutionCycle();
            BigDecimal times;
            if (cycle == 1) {
                times = new BigDecimal(30L * freq); // 每日
            } else if (cycle == 2) {
                times = new BigDecimal(4L * freq); // 每周按4周
            } else {
                times = new BigDecimal(1L * freq); // 每月
            }
            sum = sum.add(item.getPrice().multiply(times));
        }
        return sum.setScale(2, java.math.RoundingMode.HALF_UP);
    }
}
